package com.ztom.v2;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author ZhangTao
 */
public class Code52RottingOranges {

    public int orangesRotting(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        // 记录腐烂的橘子坐标
        Deque<int[]> queue = new LinkedList<>();

        // 找到初始新鲜的橘子数量
        int fresh = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    fresh++;
                } else if (grid[i][j] == 2) {
                    queue.addLast(new int[]{i, j});
                }
            }
        }
        if (fresh == 0) {
            return 0;
        }
        int minute = 0;
        while (fresh > 0 && !queue.isEmpty()) {
            minute++;
            // 当前这一分钟腐烂的橘子数
            int curMinuteCount = queue.size();
            for (int i = 0; i < curMinuteCount; i++) {
                int[] cur = queue.pollFirst();
                int r = cur[0];
                int c = cur[1];
                // 向上下左右方向扩散
                if (r > 0 && grid[r - 1][c] == 1) {
                    grid[r - 1][c] = 2;
                    queue.addLast(new int[]{r - 1, c});
                    fresh--;
                }
                if (r < m - 1 && grid[r + 1][c] == 1) {
                    grid[r + 1][c] = 2;
                    queue.addLast(new int[]{r + 1, c});
                    fresh--;
                }
                if (c > 0 && grid[r][c - 1] == 1) {
                    grid[r][c - 1] = 2;
                    queue.addLast(new int[]{r, c - 1});
                    fresh--;
                }
                if (c < n - 1 && grid[r][c + 1] == 1) {
                    grid[r][c + 1] = 2;
                    queue.addLast(new int[]{r, c + 1});
                    fresh--;
                }
            }
        }
        return fresh > 0 ? -1 : minute;
    }
}
